# Create your views here.

import json
import logging

from django.http import HttpResponse

from .models import ChessStep
from .models import ChessUser
from .netcli import EventType
from .netcli import NetCli
from .service import get_chess_steps
from .service import get_lastest_chessgrp
from .service import get_user_by_session
from .service import next_chess_step
from .utils import BussinessError
from .utils import ParamError
from .utils import Validator
from .utils import get_request_attr
from .utils import get_request_content


def index(request):
    return HttpResponse("Hello, I am five chess server")


def join_grp(request):
    try:
        session_id = get_request_attr(request=request, key='session_id')
        Validator.not_blank(session_id, 'session_id can not be blank')
        logging.info('session_id=%s', session_id)
        grp = None
        chess_user = get_user_by_session(session_id=session_id)
        if chess_user is None:
            grp = get_lastest_chessgrp()
            if grp.grp_members == 0:
                chess_user = ChessUser(session_id=session_id, grp=grp, role=ChessUser.PARTICIPANT,
                                       side=ChessUser.WHITE, status=ChessUser.ONLINE)
            else:
                chess_user = ChessUser(session_id=session_id, grp=grp, role=ChessUser.PARTICIPANT,
                                       side=ChessUser.BLACK, status=ChessUser.ONLINE)
            grp.grp_members += 1
            grp.save()
            logging.info('grp=%s', grp)
            chess_user.save()
        logging.info('user: %s', chess_user)
        return HttpResponse('%s' % RespCtx(code=RespCtx.PARAM_ERR, msg='success', data=chess_user.to_dict()))
    except ParamError as pe:
        logging.warning('params error: %s', str(pe))
        return HttpResponse('%s' % RespCtx(code=RespCtx.PARAM_ERR, msg=str(pe)))
    except BussinessError as be:
        logging.warning('business error: %s', str(be))
        return HttpResponse('%s' % RespCtx(code=RespCtx.BUSINESS_ERR, msg=str(be)))
    except Exception as e:
        logging.error('system error: %s', str(e))
        return HttpResponse('%s' % RespCtx(code=RespCtx.SYSTEM_ERR, msg=str(e)))


def position(request):
    try:
        _data = get_request_content(request)
        session_id = _data.get('session_id')
        pos_x = _data.get('pos_x')
        pos_y = _data.get('pos_y')
        Validator.not_blank(session_id, 'session_id can not be blank')
        Validator.not_null(pos_x, 'pos_x can not be null')
        Validator.not_null(pos_y, 'pos_y can not be null')
        chess_user = get_user_by_session(session_id=session_id)
        Validator.chk_bussiness((chess_user is not None), 'chess user with session_id={} not exist'.format(session_id))
        step = get_chess_steps(pos_x=pos_x, pos_y=pos_y, grp=chess_user.grp)
        logging.info('step: %s', step)
        Validator.chk_bussiness((step is None), 'step({}, {}) is already exist'.format(pos_x, pos_y))
        _next = next_chess_step(grp=chess_user.grp)
        chess_step = ChessStep(grp=chess_user.grp, chess_user=chess_user, step=_next, pos_x=pos_x, pos_y=pos_y)
        chess_step.save()
        NetCli.get_netcli().handler.send_cmd(cmd=EventType.DATA, data=str(chess_step))
        logging.info('step: %s', chess_step)
        return HttpResponse('%s' % RespCtx(code=RespCtx.SUCCESS, msg='success', data=chess_step.to_dict()))
    except ParamError as pe:
        logging.warning('params error: %s', str(pe))
        return HttpResponse('%s' % RespCtx(code=RespCtx.PARAM_ERR, msg=str(pe)))
    except BussinessError as be:
        logging.warning('business error: %s', str(be))
        return HttpResponse('%s' % RespCtx(code=RespCtx.BUSINESS_ERR, msg=str(be)))
    except Exception as e:
        logging.error('system error: %s', str(e))
        return HttpResponse('%s' % RespCtx(code=RespCtx.SYSTEM_ERR, msg=str(e)))


class RespCtx(object):
    SUCCESS = 1
    PARAM_ERR = 2
    BUSINESS_ERR = 3
    SYSTEM_ERR = 4
    UNKNOWN_ERR = 99

    def __init__(self, code=SUCCESS, msg='', data=None):
        self.code = code
        self.msg = msg
        self.data = data

    def to_dict(self):
        _dict = dict()
        _dict['code'] = self.code
        _dict['msg'] = self.msg
        _dict['data'] = self.data
        return _dict

    def __repr__(self):
        return json.dumps(self.to_dict())

    __str__ = __repr__
